<?php

namespace app\controller;

use app\BaseController;
use app\common\Snowflake;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use think\facade\Validate;

class SystemMessage extends BaseController {

    public function list()
    {
        $params = $this->request->get();
        $query = Db::name('system_messages');

        if (!empty($params['id'])) {
            $query->where('id', $params['id']);
        }
        if (!empty($params['message_id'])) {
            $query->where('message_id', $params['message_id']);
        }
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }
        if (isset($params['message_type']) && $params['message_type'] != 0) {
            $query->where('message_type', $params['message_type']);
        }
        if (isset($params['status']) && $params['status'] != 3) {
            $now = time();
            if ($params['status'] == 0) {
                $query->where('send_time', '>', date('Y-m-d H:i:s', $now));
            } else {
                $query->where('status', $params['status'])
                      ->where('send_time', '<=', date('Y-m-d H:i:s', $now));
            }
        }
        $query->order('id', 'desc');
        
        $list = $query->paginate(10);
        $data = $list->toArray();
        $statusMap = [0 => '待发送', 1 => '已发送', 2 => '已读'];
        
        foreach ($data['data'] as &$item) {
            $sendTimestamp = strtotime($item['send_time']);
            $item['status_text'] = $sendTimestamp > time() 
                ? '待发送' 
                : ($item['status'] === 2 ? '已读' : '已发送');
        }
        return json(['code' => 0, 'msg' => '获取成功', 'data' => $data]);
    }


    private function getStatusText($status, $sendTime)
    {
        $statusMap = [0 => '待发送', 1 => '已发送', 2 => '已读'];
        $sendTimestamp = strtotime($sendTime);
        return $sendTimestamp > time() ? '待发送' : $statusMap[$status] ?? '未知';
    }

    public function create()
    {
        $data = $this->request->post();
        $validate = new \think\Validate;
        $validate->rule([
            'message_type' => 'require|in:1,2,3',
            'title' => 'require',
            'content' => 'require',
            'target' => 'require',
            'send_time' => 'date' 
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 1, 'msg' => $validate->getError(), 'data' => []]);
        }
        // 确保 send_time 字段有值
        if (!isset($data['send_time'])) {
            $data['send_time'] = date('Y-m-d H:i:s'); // 如果未提供发送时间，使用当前时间
        }
        // 根据发送时间设置状态
        $sendTime = strtotime($data['send_time']);
        $currentTime = time();
        $data['status'] = $sendTime > $currentTime ? 0 : 1; // 0-待发送，1-已发送

        $snowflake = new Snowflake(1, 1);
        $data['message_id'] = $snowflake->nextId();
        $result = Db::name('system_messages')->insert($data);
        if ($result) {
            return json(['code' => 0, 'msg' => '新增成功', 'data' => []]);
        } else {
            return json(['code' => 1, 'msg' => '新增失败', 'data' => []]);
        }
    }

    // 修改 update 方法
    public function update($id)
    {
        $data = $this->request->post();
        $validate = new \think\Validate;
        $validate->rule([
            'message_type' => 'require|in:1,2,3',
            'title' => 'require',
            'content' => 'require',
            'target' => 'require',
            'send_time' => 'require'
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 1, 'msg' => $validate->getError(), 'data' => []]);
        }
        // 根据发送时间重新计算状态
        $sendTime = strtotime($data['send_time']);
        $currentTime = time();
        $data['status'] = $sendTime > $currentTime ? 0 : 1; // 0-待发送，1-已发送

        $result = Db::name('system_messages')->where('id', $id)->update($data);
        if ($result !== false) {
            return json(['code' => 0, 'msg' => '编辑成功', 'data' => []]);
        } else {
            return json(['code' => 1, 'msg' => '编辑失败', 'data' => []]);
        }
    }

    public function delete($id)
    {
        $result = Db::name('system_messages')->where('id', $id)->delete();
        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功', 'data' => []]);
        } else {
            return json(['code' => 1, 'msg' => '删除失败', 'data' => []]);
        }
    }


    public function export()
    {
        $params = $this->request->get();
        $query = Db::name('system_messages');
        if (!empty($params['id'])) {
            $query->where('id', $params['id']);
        }
        if (!empty($params['message_id'])) {
            $query->where('message_id', $params['message_id']);
        }
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }
        if (isset($params['message_type']) && $params['message_type'] != 0) {
            $query->where('message_type', $params['message_type']);
        }
        if (isset($params['status']) && $params['status'] != 3) {
            if ($params['status'] == 0) {
                $query->whereTime('send_time', '>', date('Y-m-d H:i:s'));
            } else {
                $query->where('status', $params['status'])
                      ->whereTime('send_time', '<=', date('Y-m-d H:i:s'));
            }
        }
        $data = $query->select()->toArray();
        $statusMap = [0 => '待发送', 1 => '已发送', 2 => '已读'];
        foreach ($data as &$item) {
            if ($item['send_time'] > date('Y-m-d H:i:s')) {
                $item['status'] = 0;
                $item['status_text'] = '待发送';
            } else {
                $item['status_text'] = $statusMap[$item['status']];
            }
        }
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', '雪花ID');
        $sheet->setCellValue('B1', '消息类型');
        $sheet->setCellValue('C1', '标题');
        $sheet->setCellValue('D1', '目标');
        $sheet->setCellValue('E1', '发送时间');
        $sheet->setCellValue('F1', '消息状态');
        $sheet->setCellValue('G1', '修改时间');
        $typeMap = [1 => '系统公告', 2 => '游戏资讯', 3 => '版本信息'];
        foreach ($data as $key => $row) {
            $sheet->setCellValue('A' . ($key + 2), $row['message_id']);
            $sheet->setCellValue('B' . ($key + 2), $typeMap[$row['message_type']]);
            $sheet->setCellValue('C' . ($key + 2), $row['title']);
            $sheet->setCellValue('D' . ($key + 2), $row['target']);
            $sheet->setCellValue('E' . ($key + 2), $row['send_time']);
            $sheet->setCellValue('F' . ($key + 2), $row['status_text']);
            $sheet->setCellValue('G' . ($key + 2), $row['updated_at']);
        }
        $format = $params['format'] ?? 'xlsx';
        if ($format == 'xlsx') {
            $writer = new Xlsx($spreadsheet);
            $filename = date('Ymd') . '_系统消息列表.xlsx';
        } else {
            $writer = new Csv($spreadsheet);
            $filename = date('Ymd') . '_系统消息列表.csv';
        }
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }

    //查询用户未读消息列表
    public function unreadMessages($userPhone)
    {
        $messages = Db::name('system_messages')
            ->leftJoin('user_message_read', 'system_messages.id = user_message_read.message_id AND user_message_read.user_phone = :userPhone', ['userPhone' => $userPhone])
            ->whereNull('user_message_read.id')
            ->where('system_messages.target', 'in', ['all', $userPhone])
            ->where('system_messages.status', 1) // 已发送的消息
            ->whereTime('system_messages.send_time', '<=', date('Y-m-d H:i:s'))
            ->select();
        $statusMap = [0 => '待发送', 1 => '已发送', 2 => '已读'];
        foreach ($messages as &$message) {
            if ($message['send_time'] > date('Y-m-d H:i:s')) {
                $message['status'] = 0;
                $message['status_text'] = '待发送';
            } else {
                $message['status_text'] = $statusMap[$message['status']];
            }
        }
        return json(['code' => 0, 'msg' => '获取未读消息成功', 'data' => $messages]);
    }

    //查询用户已读消息列表
    public function readMessages($userPhone)
    {
        $messages = Db::name('system_messages')
            ->join('user_message_read', 'system_messages.id = user_message_read.message_id AND user_message_read.user_phone = :userPhone', ['userPhone' => $userPhone])
            ->where('system_messages.target', 'in', ['all', $userPhone])
            ->where('system_messages.status', 1) // 已发送的消息
            ->whereTime('system_messages.send_time', '<=', date('Y-m-d H:i:s'))
            ->select();
        $statusMap = [0 => '待发送', 1 => '已发送', 2 => '已读'];
        foreach ($messages as &$message) {
            if ($message['send_time'] > date('Y-m-d H:i:s')) {
                $message['status'] = 0;
                $message['status_text'] = '待发送';
            } else {
                $message['status_text'] = $statusMap[$message['status']];
            }
        }
        return json(['code' => 0, 'msg' => '获取已读消息成功', 'data' => $messages]);
    }

    //标记消息为已读
    public function markAsRead($userPhone, $messageId)
    {
        $data = [
            'user_phone' => $userPhone,
            'message_id' => $messageId
        ];
        $result = Db::name('user_message_read')->insert($data);
        if ($result) {
            return json(['code' => 0, 'msg' => '标记为已读成功', 'data' => []]);
        } else {
            return json(['code' => 1, 'msg' => '标记为已读失败', 'data' => []]);
        }
    }
}